#include "ring_buffer.h"

// 初始化缓冲区
void ring_buffer_init(ring_buffer_t *rb, uint8_t *buffer, uint16_t size) {
    rb->buffer = buffer;
    rb->capacity = size;
    ring_buffer_reset(rb);
}

// 重置缓冲区
void ring_buffer_reset(ring_buffer_t *rb) {
    rb->head = 0;
    rb->tail = 0;
    rb->is_full = false;
}

// 写入数据
bool ring_buffer_put(ring_buffer_t *rb, uint8_t data) {
    if (ring_buffer_is_full(rb)) {
        return false;
    }

    rb->buffer[rb->head] = data;
    rb->head = (rb->head + 1) % rb->capacity;
    
    if (rb->head == rb->tail) {
        rb->is_full = true;
    }
    
    return true;
}

// 读取数据（取出）
bool ring_buffer_get(ring_buffer_t *rb, uint8_t *data) {
    if (ring_buffer_is_empty(rb)) {
        return false;
    }

    *data = rb->buffer[rb->tail];
    rb->tail = (rb->tail + 1) % rb->capacity;
    rb->is_full = false;
    
    return true;
}

// 只读不取（查看下一个要读的数据）
bool ring_buffer_peek(const ring_buffer_t *rb, uint8_t *data) {
    if (ring_buffer_is_empty(rb)) {
        return false;
    }
    
    *data = rb->buffer[rb->tail];
    return true;
}

// 按偏移量查看数据（0=最早的数据）
bool ring_buffer_peek_at(const ring_buffer_t *rb, uint16_t offset, uint8_t *data) {
    if (offset >= ring_buffer_size(rb)) {
        return false; // 偏移量超出有效范围
    }
    
    // 计算物理位置（考虑环形缓冲区环绕）
    uint16_t position = (rb->tail + offset) % rb->capacity;
    *data = rb->buffer[position];
    return true;
}

// 获取当前数据量
uint16_t ring_buffer_size(const ring_buffer_t *rb) {
    if (rb->is_full) {
        return rb->capacity;
    }
    
    if (rb->head >= rb->tail) {
        return rb->head - rb->tail;
    }
    
    return rb->capacity - rb->tail + rb->head;
}

// 检查是否为空
bool ring_buffer_is_empty(const ring_buffer_t *rb) {
    return (!rb->is_full && (rb->head == rb->tail));
}

// 检查是否为满
bool ring_buffer_is_full(const ring_buffer_t *rb) {
    return rb->is_full;
}